﻿#region Using Directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web.UI;
using System.Web.UI.Design;

using SPL.Entities;
using SPL.Data;
using SPL.Data.Bases;
using SPL.Services;
#endregion

namespace SPL.Web.Data
{
	/// <summary>
	/// Represents the DataRepository.KvtProvider object that provides
	/// data to data-bound controls in multi-tier Web application architectures.
	/// </summary>
	[Designer(typeof(KvtDataSourceDesigner))]
	public class KvtDataSource : ProviderDataSource<Kvt, KvtKey>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the KvtDataSource class.
		/// </summary>
		public KvtDataSource() : base(new KvtService())
		{
		}

		#endregion Constructors
		
		#region Properties
		
		/// <summary>
		/// Gets a reference to the KvtDataSourceView used by the KvtDataSource.
		/// </summary>
		protected KvtDataSourceView KvtView
		{
			get { return ( View as KvtDataSourceView ); }
		}
		
		/// <summary>
		/// Gets or sets the name of the method or function that
		/// the KvtDataSource control invokes to retrieve data.
		/// </summary>
		public KvtSelectMethod SelectMethod
		{
			get
			{
				KvtSelectMethod selectMethod = KvtSelectMethod.GetAll;
				Object method = ViewState["SelectMethod"];
				if ( method != null )
				{
					selectMethod = (KvtSelectMethod) method;
				}
				return selectMethod;
			}
			set { ViewState["SelectMethod"] = value; }
		}

		#endregion Properties
		
		#region Methods

		/// <summary>
		/// Creates a new instance of the KvtDataSourceView class that is to be
		/// used by the KvtDataSource.
		/// </summary>
		/// <returns>An instance of the KvtDataSourceView class.</returns>
		protected override BaseDataSourceView<Kvt, KvtKey> GetNewDataSourceView()
		{
			return new KvtDataSourceView(this, DefaultViewName);
		}
		
		/// <summary>
        /// Creates a cache hashing key based on the startIndex, pageSize and the SelectMethod being used.
        /// </summary>
        /// <param name="startIndex">The current start row index.</param>
        /// <param name="pageSize">The current page size.</param>
        /// <returns>A string that can be used as a key for caching purposes.</returns>
		protected override string CacheHashKey(int startIndex, int pageSize)
        {
			return String.Format("{0}:{1}:{2}", SelectMethod, startIndex, pageSize);
        }
		
		#endregion Methods
	}
	
	/// <summary>
	/// Supports the KvtDataSource control and provides an interface for
	/// data-bound controls to perform data operations with business and data objects.
	/// </summary>
	public class KvtDataSourceView : ProviderDataSourceView<Kvt, KvtKey>
	{
		#region Declarations

		#endregion Declarations
		
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the KvtDataSourceView class.
		/// </summary>
		/// <param name="owner">A reference to the KvtDataSource which created this instance.</param>
		/// <param name="viewName">The name of the view.</param>
		public KvtDataSourceView(KvtDataSource owner, String viewName)
			: base(owner, viewName)
		{
		}
		
		#endregion Constructors
		
		#region Properties

		/// <summary>
		/// Gets a strongly-typed reference to the Owner property.
		/// </summary>
		internal KvtDataSource KvtOwner
		{
			get { return Owner as KvtDataSource; }
		}

		/// <summary>
		/// Gets or sets the name of the method or function that
		/// the DataSource control invokes to retrieve data.
		/// </summary>
		internal KvtSelectMethod SelectMethod
		{
			get { return KvtOwner.SelectMethod; }
			set { KvtOwner.SelectMethod = value; }
		}

		/// <summary>
		/// Gets a strongly typed reference to the Provider property.
		/// </summary>
		internal KvtService KvtProvider
		{
			get { return Provider as KvtService; }
		}

		#endregion Properties
		
		#region Methods
		
		/// <summary>
		/// Gets a collection of Entity objects based on the value of the SelectMethod property.
		/// </summary>
		/// <param name="count">The total number of rows in the DataSource.</param>
		/// <returns>A collection of Entity objects.</returns>
		protected override IList<Kvt> GetSelectData(out int count)
		{
			Hashtable values = CollectionsUtil.CreateCaseInsensitiveHashtable(GetParameterValues());
			Hashtable customOutput = CollectionsUtil.CreateCaseInsensitiveHashtable();
			IList<Kvt> results = null;
			Kvt item;
			count = 0;
			
			System.Int64 id;
			System.Int32 status;
			System.Int32 inputUser;
			System.Int64? hid_nullable;

			switch ( SelectMethod )
			{
				case KvtSelectMethod.Get:
					KvtKey entityKey  = new KvtKey();
					entityKey.Load(values);
					item = KvtProvider.Get(entityKey);
					results = new TList<Kvt>();
					if ( item != null ) results.Add(item);
					count = results.Count;
					break;
				case KvtSelectMethod.GetAll:
                    results = KvtProvider.GetAll(StartIndex, PageSize, out count);
                    break;
				case KvtSelectMethod.GetPaged:
					results = KvtProvider.GetPaged(WhereClause, OrderBy, PageIndex, PageSize, out count);
					break;
				case KvtSelectMethod.Find:
					if ( FilterParameters != null )
						results = KvtProvider.Find(FilterParameters, OrderBy, StartIndex, PageSize, out count);
					else
						results = KvtProvider.Find(WhereClause, StartIndex, PageSize, out count);
                    break;
				// PK
				case KvtSelectMethod.GetById:
					id = ( values["Id"] != null ) ? (System.Int64) EntityUtil.ChangeType(values["Id"], typeof(System.Int64)) : (long)0;
					item = KvtProvider.GetById(id);
					results = new TList<Kvt>();
					if ( item != null ) results.Add(item);
					count = results.Count;
					break;
				// IX
				// FK
				case KvtSelectMethod.GetByStatus:
					status = ( values["Status"] != null ) ? (System.Int32) EntityUtil.ChangeType(values["Status"], typeof(System.Int32)) : (int)0;
					results = KvtProvider.GetByStatus(status, this.StartIndex, this.PageSize, out count);
					break;
				case KvtSelectMethod.GetByInputUser:
					inputUser = ( values["InputUser"] != null ) ? (System.Int32) EntityUtil.ChangeType(values["InputUser"], typeof(System.Int32)) : (int)0;
					results = KvtProvider.GetByInputUser(inputUser, this.StartIndex, this.PageSize, out count);
					break;
				case KvtSelectMethod.GetByHid:
					hid_nullable = (System.Int64?) EntityUtil.ChangeType(values["Hid"], typeof(System.Int64?));
					results = KvtProvider.GetByHid(hid_nullable, this.StartIndex, this.PageSize, out count);
					break;
				// M:M
				// Custom
				default:
					break;
			}

			if ( results != null && count < 1 )
			{
				count = results.Count;

				if ( !String.IsNullOrEmpty(CustomMethodRecordCountParamName) )
				{
					object objCustomCount = EntityUtil.ChangeType(customOutput[CustomMethodRecordCountParamName], typeof(Int32));
					
					if ( objCustomCount != null )
					{
						count = (int) objCustomCount;
					}
				}
			}
			
			return results;
		}
		
		/// <summary>
		/// Gets the values of any supplied parameters for internal caching.
		/// </summary>
		/// <param name="values">An IDictionary object of name/value pairs.</param>
		protected override void GetSelectParameters(IDictionary values)
		{
			if ( SelectMethod == KvtSelectMethod.Get || SelectMethod == KvtSelectMethod.GetById )
			{
				EntityId = GetEntityKey(values);
			}
		}

		/// <summary>
		/// Performs a DeepLoad operation for the current entity if it has
		/// not already been performed.
		/// </summary>
		internal override void DeepLoad()
		{
			if ( !IsDeepLoaded )
			{
				Kvt entity = GetCurrentEntity();
				
				if ( entity != null )
				{
					// init transaction manager
					GetTransactionManager();
					// execute deep load method
					KvtProvider.DeepLoad(GetCurrentEntity(), EnableRecursiveDeepLoad);
					// set loaded flag
					IsDeepLoaded = true;
				}
			}
		}

		/// <summary>
		/// Performs a DeepLoad operation on the specified entity collection.
		/// </summary>
		/// <param name="entityList"></param>
		/// <param name="properties"></param>
		internal override void DeepLoad(TList<Kvt> entityList, ProviderDataSourceDeepLoadList properties)
		{
			// init transaction manager
			GetTransactionManager();
			// execute deep load method
			KvtProvider.DeepLoad(entityList, properties.Recursive, properties.Method, properties.GetTypes());
		}

		#endregion Select Methods
	}
	
	#region KvtDataSourceDesigner

	/// <summary>
	/// Provides design-time support in a design host for the KvtDataSource class.
	/// </summary>
	public class KvtDataSourceDesigner : ProviderDataSourceDesigner<Kvt, KvtKey>
	{
		/// <summary>
		/// Initializes a new instance of the KvtDataSourceDesigner class.
		/// </summary>
		public KvtDataSourceDesigner()
		{
		}

		/// <summary>
		/// Gets or sets the SelectMethod property.
		/// </summary>
		public KvtSelectMethod SelectMethod
		{
			get { return ((KvtDataSource) DataSource).SelectMethod; }
			set { SetPropertyValue("SelectMethod", value); }
		}

		/// <summary>Gets the designer action list collection for this designer.</summary>
		/// <returns>The <see cref="T:System.ComponentModel.Design.DesignerActionListCollection"/>
		/// associated with this designer.</returns>
		public override DesignerActionListCollection ActionLists
		{
			get
			{
				DesignerActionListCollection actions = new DesignerActionListCollection();
				actions.Add(new KvtDataSourceActionList(this));
				actions.AddRange(base.ActionLists);
				return actions;
			}
		}
	}

	#region KvtDataSourceActionList

	/// <summary>
	/// Supports the KvtDataSourceDesigner class.
	/// </summary>
	internal class KvtDataSourceActionList : DesignerActionList
	{
		private KvtDataSourceDesigner _designer;

		/// <summary>
		/// Initializes a new instance of the KvtDataSourceActionList class.
		/// </summary>
		/// <param name="designer"></param>
		public KvtDataSourceActionList(KvtDataSourceDesigner designer) : base(designer.Component)
		{
			_designer = designer;
		}

		/// <summary>
		/// Gets or sets the SelectMethod property.
		/// </summary>
		public KvtSelectMethod SelectMethod
		{
			get { return _designer.SelectMethod; }
			set { _designer.SelectMethod = value; }
		}

		/// <summary>
		/// Returns the collection of <see cref="T:System.ComponentModel.Design.DesignerActionItem"/>
		/// objects contained in the list.
		/// </summary>
		/// <returns>A <see cref="T:System.ComponentModel.Design.DesignerActionItem"/>
		/// array that contains the items in this list.</returns>
		public override DesignerActionItemCollection GetSortedActionItems()
		{
			DesignerActionItemCollection items = new DesignerActionItemCollection();
			items.Add(new DesignerActionPropertyItem("SelectMethod", "Select Method", "Methods"));
			return items;
		}
	}

	#endregion KvtDataSourceActionList
	
	#endregion KvtDataSourceDesigner
	
	#region KvtSelectMethod
	
	/// <summary>
	/// Enumeration of method names available for the KvtDataSource.SelectMethod property.
	/// </summary>
	public enum KvtSelectMethod
	{
		/// <summary>
		/// Represents the Get method.
		/// </summary>
		Get,
		/// <summary>
		/// Represents the GetAll method.
		/// </summary>
		GetAll,
		/// <summary>
		/// Represents the GetPaged method.
		/// </summary>
		GetPaged,
		/// <summary>
		/// Represents the Find method.
		/// </summary>
		Find,
		/// <summary>
		/// Represents the GetById method.
		/// </summary>
		GetById,
		/// <summary>
		/// Represents the GetByStatus method.
		/// </summary>
		GetByStatus,
		/// <summary>
		/// Represents the GetByInputUser method.
		/// </summary>
		GetByInputUser,
		/// <summary>
		/// Represents the GetByHid method.
		/// </summary>
		GetByHid
	}
	
	#endregion KvtSelectMethod

	#region KvtFilter
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilter&lt;EntityColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Kvt"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class KvtFilter : SqlFilter<KvtColumn>
	{
	}
	
	#endregion KvtFilter

	#region KvtExpressionBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlExpressionBuilder&lt;EntityColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Kvt"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class KvtExpressionBuilder : SqlExpressionBuilder<KvtColumn>
	{
	}
	
	#endregion KvtExpressionBuilder	

	#region KvtProperty
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ChildEntityProperty&lt;KvtChildEntityTypes&gt;"/> class
	/// that is used exclusively with a <see cref="Kvt"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class KvtProperty : ChildEntityProperty<KvtChildEntityTypes>
	{
	}
	
	#endregion KvtProperty
}

